<?php
/**
 * 第三方账号登录和注册行为
 *
 * @copyright  Copyright (c) 中国追溯
 * @since      File available since Release v1.1
 */
defined('InShopNC') or exit('Access Invalid!');
class connect_api_hunterLogic {

    /**
     * 登录开关状态
     * @return array
     */
    public function getStateInfo() {
        $state_array = array();
        $state_array['pc_qq'] = C('qq_isuse');//PC网页端的QQ互联
        $state_array['pc_sn'] = C('sina_isuse');//PC网页端的新浪微博
        $state_array['connect_qq'] = C('app_qq_isuse');//手机客户端的QQ互联
        $state_array['connect_sn'] = C('app_sina_isuse');//手机客户端的新浪微博
        $state_array['connect_wx'] = C('app_weixin_isuse');//手机客户端的微信登录
        $state_array['connect_wap_wx'] = C('wap_weixin_isuse');//wap的微信登录
        $state_array['connect_sms_reg'] = C('sms_register');//手机注册
        $state_array['connect_sms_lgn'] = C('sms_login');//手机登录
        $state_array['connect_sms_psd'] = C('sms_password');//手机短信找回密码
        return $state_array;
    }

    /**
     * 获取wap的微信登录
     * @return string
     */
    public function getWxOAuth2Url(){
        $weixin_appid = C('wap_weixin_appid');

        $api_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$weixin_appid.
            '&redirect_uri='.urlencode(MOBILE_SITE_URL.'/index.php?act=connect&op=index').
            '&response_type=code&scope=snsapi_userinfo&state='.base64_encode($_GET['ref_url']).'#wechat_redirect';
        return $api_url;
    }

    /**
     * 发送手机动态码
     * @param string $phone
     * @param string $log_type
     * @return array
     */
    public function sendCaptcha($phone, $log_type){
        $model_sms_log = Model('sms_log');
        $state = true;
        $msg = '手机动态码发送成功';
        $sms_log = $this->ipCaptcha($log_type);
        if(!empty($sms_log) && ($sms_log['add_time'] > TIMESTAMP-DEFAULT_CONNECT_SMS_TIME)) {//同一IP[n]秒内只能发一条短信
            $state = false;
            $msg = '同一IP地址'.DEFAULT_CONNECT_SMS_TIME.'秒内，请勿多次获取动态码！';
        }
        $condition = array();
        $condition['log_phone'] = $phone;
        $condition['log_type'] = $log_type;
        $sms_log = $model_sms_log->getSmsInfo($condition);
        if($state && !empty($sms_log) && ($sms_log['add_time'] > TIMESTAMP-DEFAULT_CONNECT_SMS_TIME)) {//同一手机号IP[n]秒内只能发一条短信
            $state = false;
            $msg = '同一手机号'.DEFAULT_CONNECT_SMS_TIME.'秒内，请勿多次获取动态码！';
        }
        $time24 = TIMESTAMP-60*60*24;
        $condition = array();
        $condition['log_phone'] = $phone;
        $condition['add_time'] = array('egt',$time24);
        $num = $model_sms_log->getSmsCount($condition);
        if($state && $num >= DEFAULT_CONNECT_SMS_PHONE) {//同一手机号24小时内只能发5条短信
            $state = false;
            $msg = '同一手机号24小时内，请勿多次获取动态码！';
        }
        $condition = array();
        $condition['log_ip'] = getIp();
        $condition['add_time'] = array('egt',$time24);
        $num = $model_sms_log->getSmsCount($condition);
        if($state && $num >= DEFAULT_CONNECT_SMS_IP) {//同一IP24小时内只能发20条短信
            $state = false;
            $msg = '同一IP24小时内，请勿多次获取动态码！';
        }
        if($state == true) {
            $log_array = array();
            $model_hunter = Model('hunter');
            $hunter = $model_hunter->getInfo(array('hunter_mobile'=> $phone));
            $captcha = rand(100000, 999999);
            $log_msg = '【'.C('site_name').'】您于'.date("Y-m-d");
            switch ($log_type) {
                case '1':
                    if(C('sms_register') != 1) {
                        $state = false;
                        $msg = '系统没有开启手机注册功能';
                    }
                    if(!empty($hunter)) {//检查手机号是否已被注册
                        $state = false;
                        $msg = '当前手机号已被注册，请更换其他号码。';
                    }
                    $log_msg .= '申请注册会员，短信验证码：'.$captcha.'。';
                    break;
                case '2':
                    if(C('sms_login') != 1) {
                        $state = false;
                        $msg = '系统没有开启手机登录功能';
                    }
                    if(empty($hunter)) {//检查手机号是否已绑定会员
                        $state = false;
                        $msg = '当前手机号未注册，请检查号码是否正确。';
                    }
                    $log_msg .= '申请登录，短信验证码：'.$captcha.'。';
                    $log_array['hunter_id'] = $hunter['hunter_id'];
                    $log_array['hunter_name'] = $hunter['hunter_name'];
                    break;
                case '3':
                    if(C('sms_password') != 1) {
                        $state = false;
                        $msg = '系统没有开启手机找回密码功能';
                    }
                    if(empty($hunter)) {//检查手机号是否已绑定会员
                        $state = false;
                        $msg = '当前手机号未注册，请检查号码是否正确。';
                    }
                    $log_msg .= '申请重置登录密码，短信验证码：'.$captcha.'。';
                    $log_array['hunter_id'] = $hunter['hunter_id'];
                    $log_array['hunter_name'] = $hunter['hunter_name'];
                    break;
                default:
                    $state = false;
                    $msg = '参数错误';
                    break;
            }
            if($state == true){
                $sms = new Sms();
                $result = $sms->send($phone,$log_msg);
                if($result){
                    $log_array['log_phone'] = $phone;
                    $log_array['log_captcha'] = $captcha;
                    $log_array['log_ip'] = getIp();
                    $log_array['log_msg'] = $log_msg;
                    $log_array['log_type'] = $log_type;
                    $log_array['add_time'] = TIMESTAMP;
                    $model_sms_log->addSms($log_array);
                } else {
                    $state = false;
                    $msg = '手机短信发送失败';
                }
            }
        }
        $state_data = array(
            'state' => $state,
            'sms_time' => DEFAULT_CONNECT_SMS_TIME,
            'msg' => $msg
        );
        return $state_data;
    }

    /**
     * 手机注册
     * @param string $phone
     * @param string $captcha
     * @param string $password
     * @param string $client
     * @return array
     */
    public function smsRegister($phone, $captcha, $password, $client){
        $state_data = $this->checkSmsCaptcha($phone, $captcha, 1);//再次进行动态码验证
        $state = $state_data['state'];
        if($state == true){
            $model_hunter = Model('hunter');
            $hunter = $model_hunter->getInfo(array('hunter_mobile'=> $phone));
            if(!empty($hunter)) {//检查手机号是否已被注册
                $state_data['state'] = false;
                $state_data['msg'] = '当前手机号已被注册，请更换其他号码。';
                return $state_data;
            }
            $num = substr($phone,-4);
            $hunter_name = $this->getName('mb', $num);
            $hunter = array();
            $hunter['hunter_name'] = $hunter_name;
            $hunter['hunter_passwd'] = $password;
            $hunter['hunter_email'] = '';
            $hunter['hunter_mobile'] = $phone;
            $hunter['hunter_mobile_bind'] = 1;
            $result = $model_hunter->addhunter($hunter);
            if($result) {
                $hunter = $model_hunter->gethunterInfo(array('hunter_name'=> $hunter_name));
                $hunter_id = $hunter['hunter_id'];
                $token = $this->getUserToken($hunter, $client);
                if($token) {
                    $state_data['key'] = $token;
                    $state_data['username'] = $hunter_name;
                    $state_data['userid'] = $hunter_id;
                } else {
                    $state_data['msg'] = '会员登录失败';
                }
            } else {
                $state_data['msg'] = '会员信息保存错误';
            }
        }
        return $state_data;
    }

    /**
     * 手机找回密码
     * @param string $phone
     * @param string $captcha
     * @param string $password
     * @param string $client
     * @return array
     */
    public function smsPassword($phone, $captcha, $password, $client){
        $state_data = $this->checkSmsCaptcha($phone, $captcha, 3);//再次进行动态码验证
        $state = $state_data['state'];
        if($state == true){
            $model_hunter = Model('hunter');
            $hunter = $model_hunter->gethunterInfo(array('hunter_mobile'=> $phone));//检查手机号是否已被注册
            if(!empty($hunter)) {
                $new_password = md5($password);
                $model_hunter->edithunter(array('hunter_id'=> $hunter['hunter_id']),array('hunter_passwd'=> $new_password));
                $hunter_id = $hunter['hunter_id'];
                $hunter_name = $hunter['hunter_name'];
                $token = $this->getUserToken($hunter, $client);
                if($token) {
                    $state_data['key'] = $token;
                    $state_data['username'] = $hunter_name;
                    $state_data['userid'] = $hunter_id;
                } else {
                    $state_data['msg'] = '会员登录失败';
                }
            }
        }
        return $state_data;
    }

    /**
     * 验证动态码
     * @param string $phone
     * @param string $captcha
     * @param string $log_type
     * @return array
     */
    public function checkSmsCaptcha($phone, $captcha, $log_type){
        $state = true;
        $msg = '手机动态码验证成功';
        $sms_log = $this->getLogCaptcha($phone, $captcha, $log_type);
        if(empty($sms_log) || ($sms_log['add_time'] < TIMESTAMP-1800)) {//半小时内进行验证为有效
            $state = false;
            $msg = '动态码错误或已过期，重新输入';
        }
        $state_data = array(
            'state' => $state,
            'msg' => $msg
        );
        return $state_data;
    }

    /**
     * 查询手机动态码
     * @param string $phone
     * @param string $captcha
     * @param string $log_type
     * @return array
     */
    public function getLogCaptcha($phone, $captcha, $log_type){
        $condition = array();
        $condition['log_phone'] = $phone;
        $condition['log_captcha'] = $captcha;
        $condition['log_type'] = intval($log_type);
        $model_sms_log = Model('sms_log');
        $sms_log = $model_sms_log->getSmsInfo($condition);
        return $sms_log;
    }

    /**
     * 获取猎人移动端登录令牌
     * @param array $hunter
     * @param string $client
     * @return array
     */
    public function getUserToken($hunter, $client){
        $model_mb_hunter_token = Model('mb_hunter_token');
        $mb_hunter_token_info = array();
        $token = md5($hunter['hunter_name'] . strval(TIMESTAMP) . strval(rand(0,999999)));
        $mb_hunter_token_info['hunter_id'] = $hunter['hunter_id'];
        $mb_hunter_token_info['hunter_name'] = $hunter['hunter_name'];
        $mb_hunter_token_info['token'] = $token;
        $mb_hunter_token_info['login_time'] = TIMESTAMP;
        $mb_hunter_token_info['client_type'] = $client;
        $result = $model_mb_hunter_token->addMbUserToken($mb_hunter_token_info);
        if ($result) {
            /*$model_hunter = Model('hunter');
            //添加会员积分
            $model_hunter->addPoint($hunter);
            //添加会员经验值
            $model_hunter->addExppoint($hunter);
            $update_info    = array(
                'hunter_login_num'=> ($hunter['hunter_login_num']+1),
                'hunter_login_time'=> TIMESTAMP,
                'hunter_old_login_time'=> $hunter['hunter_login_time'],
                'hunter_login_ip'=> getIp(),
                'hunter_old_login_ip'=> $hunter['hunter_login_ip']
            );
            $model_hunter->edithunter(array('hunter_id'=>$hunter['hunter_id']),$update_info);*/

            //重新登录后以前的令牌失效
            $condition = array(
                'token_id'  => array('neq', $result),
                'hunter_id' => (int)$hunter['hunter_id'],
                'client_type' => $client
            );
            $condition['hunter_id'] = $hunter['hunter_id'];
            $condition['client_type'] = $client;
            $model_mb_hunter_token->delMbUserToken($condition);

            return $token;
        } else {
            return 0;
        }
    }

    /**
     * 获得可用的会员名
     * @param string $prefix
     * @param int $num
     * @return string
     */
    public function gethunterName($prefix = 'user_', $num = 0){
        if ($num < 1) {
            $num = rand(100, 899);
        }
        if (strlen($prefix) < 3) {
            $hunter_name = $prefix.$num;
        } else {
            $hunter_name = $prefix;
        }
        $model_hunter = Model('hunter');
        if (strlen($hunter_name) < 6) {
            $hunter_name = $hunter_name.$num;
        }
        $hunter = $model_hunter->getInfo(array('hunter_name'=> $hunter_name));
        if(!empty($hunter)) {
            for ($i = 1;$i < 999;$i++) {
                $num += $i;
                $hunter_name = $prefix.$num;
                if (strlen($hunter_name) < 6) {
                    $hunter_name = 'user_'.$hunter_name;
                }
                $hunter = $model_hunter->getInfo(array('hunter_name'=> $hunter_name));
                if(empty($hunter)) {//查询为空表示当前会员名可用
                    break;
                }
            }
        }
        return $hunter_name;
    }

    /**
     * 按IP查询手机动态码
     * @param string $log_type
     * @return array
     */
    public function ipCaptcha($log_type = ''){
        $condition = array();
        $condition['log_ip'] = getIp();
        $log_type = intval($log_type);
        if ($log_type > 0) {
            $condition['log_type'] = $log_type;//短信类型:1为注册,2为登录,3为找回密码
        }
        $model_sms_log = Model('sms_log');
        $sms_log = $model_sms_log->getSmsInfo($condition);
        return $sms_log;
    }

    /**
     * 获取微信小程序的sessionkey
     * @param  string $code 小程序code
     * @return array
     */
    public function  getAppletSessionKey($code = '', $applet_type = 'applet_wx'){

        $applet_appid = empty(C('wx_applet_appid')) ? 'wx5d199ac85b0760ab' : C('wx_applet_appid');
        $applet_secret = empty(C('wx_applet_secret')) ? '45c8d8bbc2b02f4045ef1717fe33d31d' : C('wx_applet_secret');
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $applet_appid . '&secret=' . $applet_secret . '&js_code=' . $code . '&grant_type=authorization_code';
        $applet_info = $this->getUrlContents($url);
        $applet_info = json_decode($applet_info, true);

        // 生成 applet端，登陆密钥
        $model_applet = Model('applet_user_secret');
        $openid = isset($applet_info['openid']) ? $applet_info['openid'] : '';
        $unionid = isset($applet_info['unionid']) ? $applet_info['unionid'] : '';
        $session_key = isset($applet_info['session_key']) ? $applet_info['session_key'] : '';

        $applet_info['login_secret'] = $model_applet->addAppletUserSecret($openid, $session_key);
        if ($applet_info['login_secret'] === false) return false;
        return $applet_info;
    }

    /**
     * 得到小程序加密内容
     * @param  string $session_key    微信小程序的sessionkey
     * @param  string $iv             加密算法的初始向量
     * @param  string $encrypted_data 包括敏感数据在内的完整用户信息的加密数据
     * @return array
     */
    public function getAppletMoblie($session_key, $iv, $encrypted_data)
    {
        require_once(BASE_CORE_PATH . '/framework/extend/wechat_applet/wxBizDataCrypt.php');

        $applet_appid = empty(C('wx_applet_appid')) ? 'wx5d199ac85b0760ab' : C('wx_applet_appid');
        $wx_biz = new WXBizDataCrypt($applet_appid, $session_key);
        $err_code = $wx_biz->decryptData($encrypted_data, $iv, $decode_data);
        return array('err_code' => $err_code, 'decode_data' => json_decode($decode_data));
    }

    /**
     * 处理小程序传递的登陆/注册数据
     * @param  array  $dispose_data 处理数据
     * @param  string $applet_type     小程序类型
     * @return array
     */
    public function disposeAppletData(array $dispose_data, $applet_type = 'applet_wx')
    {
        if (!isset($dispose_data['openid']) || empty($dispose_data['openid'])) return array();

        if(!isset($dispose_data['unionid']) || empty($dispose_data['unionid'])) {
            $dispose_data['unionid'] = $dispose_data['openid'];
        }
        $weixin_info = array();
        $weixin_info['unionid'] = $dispose_data['unionid'];
        $weixin_info['nickname'] = $dispose_data['nickname'];
        $weixin_info['openid'] = $dispose_data['openid'];
        $dispose_data['weixin_info'] = serialize($weixin_info);
        return $dispose_data;
    }

    /**
     * 小程序自动登陆
     * @param  array  $user_info 用户信息
     * @return array
     */
    public function appletAutoLogin(array $user_info, $applet_type = 'applet_wx')
    {
        $result_data = ['state' => false, 'msg' => ''];
        $unionid = isset($user_info['unionid']) ? $user_info['unionid'] : '';
        if (empty($unionid)) {
            $result_data['msg'] = '非法请求：unionid为必须！';
            return $result_data;
        }

        $model_hunter = Model('hunter');
        $model_applet = Model('applet_user_secret');/*小程序用户密钥模型*/
        $applet_openid_wx = isset($user_info['openid']) ? $user_info['openid'] : '';
        $login_secret = isset($user_info['login_secret']) ? $user_info['login_secret'] : $login_data = array();
        $token = 0;
        $callback_data = array();   //登陆回调修改数据
        $callback_where = array();   //登陆回调修改条件

        //校验，登陆密钥
        $secret_status = $model_applet->verifyAppletSecretStatus($applet_openid_wx, $login_secret, $applet_type);
        if ($secret_status !== true) {
            $result_data['msg'] = '小程序登陆密钥失效！';
            return $result_data;
        }
        //是否存在手机号码
        $hunter_mobile = isset($user_info['mobile']) ? $user_info['mobile'] : '';
        $phone_hunter_data = array();   //绑定手机号码的会员信息
        $phone_correct_marking = false; //手机格式正确标识

        if ($hunter_mobile && (strlen($hunter_mobile) === 11)) {
            $phone_correct_marking = true;
            $phone_hunter_data = $model_hunter->getInfo(array('hunter_mobile' => $hunter_mobile, 'hunter_mobile_bind' => 1));  //是否存在绑定手机的账号
        }

        if (!empty($phone_hunter_data)) {   //存在绑定手机的账号
            $hunter_state = $this->checkhunter($phone_hunter_data, 'applet_wx');
            if ($hunter_state !== true) {
                $result_data['msg'] = '非法请求：该mobile已经被禁用！';
                return $result_data;
            }

            //获取猎人移动端登录标识
            $token = $this->getUserToken($phone_hunter_data, $applet_type);

            $hunter_name = $phone_hunter_data['hunter_name'];
            $hunter_id = $phone_hunter_data['hunter_id'];
            //检查是否修改数据微信unionid，applet_wx_openid
            if (($phone_hunter_data['weixin_unionid'] !== $unionid) || ($phone_hunter_data['applet_wx_openid'] !== $applet_openid_wx)) {
                $callback_data = array(
                    'weixin_unionid' => $unionid,
                    'applet_wx_openid' => $applet_openid_wx
                );
                $callback_where = array(
                    'hunter_id' => (int)$phone_hunter_data['hunter_id']
                );
            }

        } else {    //检查是否存在绑定unionid的账号

            $unionid_hunter_data = $model_hunter->getInfo(array('weixin_unionid'=> $unionid));  //是否存在绑定unionid的账号

            if(!empty($unionid_hunter_data)) {   //存在绑定unionid账号
                $hunter_state = $this->checkhunter($unionid_hunter_data, 'applet_wx');

                if ($hunter_state !== true) {
                    $result_data['msg'] = '非法请求：该unionid已经被禁用！';
                    return $result_data;
                }

                //获取移动端登录标识
                $token = $this->getUserToken($unionid_hunter_data, $applet_type);

                $hunter_name = $unionid_hunter_data['hunter_name'];
                $hunter_id = $unionid_hunter_data['hunter_id'];

                $callback_data = array();

                //检查 applet_wx_openid 是否一致
                if ($unionid_hunter_data['applet_wx_openid'] !== $applet_openid_wx) {
                    $callback_data['applet_wx_openid'] = $applet_openid_wx;
                }

                //检查是否修改数据绑定手机  -- 该手机号码必须先检查是否已经绑定会员
                if (($phone_correct_marking === true) && (($unionid_hunter_data['hunter_mobile'] !== $hunter_mobile) || ($unionid_hunter_data['hunter_mobile_bind'] != 1))) {
                    $callback_data['hunter_mobile'] = $hunter_mobile;
                    $callback_data['hunter_mobile_bind'] = 1;
                }

                $callback_where = array(
                    'hunter_id' => (int)$unionid_hunter_data['hunter_id']
                );

            } else {    //不存在，自动创建新账户，并登陆，可能存在手机，可能不存在
                $info_data = $this->wxRegister($user_info, $applet_type);
                $token = $info_data['token'];
                $hunter = $info_data['hunter'];
                $hunter_name = $hunter['hunter_name'];
                $hunter_id = $hunter['hunter_id'];
                $login_data['password'] = $hunter['hunter_passwd'];

            }

        }

        //校验token生成情况
        if (!$token) {
            $result_data['msg'] = '会员登录失败！';
            return $result_data;
        }

        //判断是否需要修改数据
        if (!empty($callback_data) && !empty($callback_where)) {
            $model_hunter->edit($callback_where, $callback_data);
        }

        //获取登陆的用户信息
        $hunter = $model_hunter->getInfo(array('hunter_id'=> $hunter_id));
        if (empty($hunter)) {
            $result_data['msg'] = '不存在该会员信息！';
            return $result_data;
        }

        $login_data['key'] = $token;
        $login_data['username'] = $hunter['hunter_name'];
        $login_data['userid'] = $hunter['hunter_id'];
        if (isset($hunter['hunter_mobile']) && $hunter['hunter_mobile'] && ($hunter['hunter_mobile_bind'] === '1')) {
            $login_data['hunter_mobile'] =  $hunter['hunter_mobile'];
        }

        $result_data = ['state' => true, 'msg' => '登陆成功！', 'login_data' => $login_data];

        return $result_data;
    }


    /**
     * 检查会员状态
     * @param  array  $hunter      会议数据
     * @param  string $applet_type 小程序类型
     * @return true - 正常 / false - 禁用
     */
    public function checkhunter(array $hunter, $applet_type = 'applet_wx')
    {
        $hunter_state = isset($hunter['hunter_state']) ? $hunter['hunter_state'] : false;
        return (bool)$hunter_state;
    }


    /**
     * 微信注册
     * @param string $user_info
     * @param string $client
     * @return array
     */
    public function wxRegister($user_info, $client){
        $state_data = array();
        $state_data['token'] = 0;
        $unionid = $user_info['unionid'];
        $nickname = $user_info['nickname'];
        if (!preg_match('/^[A-Za-z0-9\x{4e00}-\x{9fa5}_]/u',$nickname)) $nickname='wx';
        $rand = rand(100, 899);
        $hunter_name = $this->gethunterName($nickname, $rand);
        $password = rand(100000, 999999);
        $hunter = array();
        $hunter['hunter_name'] = $hunter_name;
        $hunter['hunter_passwd'] = $password;
        $hunter['hunter_email'] = '';
        $hunter['weixin_unionid'] = $unionid;
        $hunter['weixin_info'] = $user_info['weixin_info'];
        // 如果是微信小程序注册
        if ($client === 'applet_wx') {
            $hunter['applet_wx_openid'] = isset($user_info['openid']) ? $user_info['openid'] : $unionid;
            if (isset($user_info['mobile']) && !empty($user_info['mobile'])) {
                $hunter['hunter_mobile'] = $user_info['mobile'];
                $hunter['hunter_mobile_bind'] = 1;
            }
        }

        $model_hunter = Model('hunter');

        $result = $model_hunter->add($hunter);
        if($result) {
            $headimgurl = $user_info['headimgurl'];//用户头像，最后一个数值代表正方形头像大小（有0、46、64、96、132数值可选，0代表640*640正方形头像）
            $avatar = @copy($headimgurl,BASE_UPLOAD_PATH.'/'.ATTACH_AVATAR."/avatar_$result.jpg");
            if($avatar) {
                $model_hunter->edithunter(array('hunter_id'=> $result),array('hunter_avatar'=> "avatar_$result.jpg"));
            }
            $hunter = $model_hunter->getInfo(array('hunter_name'=> $hunter_name));
            if($client == 'www'){//网站注册
                $hunter['password'] = $password;
                return $hunter;
            }
            $hunter_id = $hunter['hunter_id'];
            $token = $this->getUserToken($hunter, $client);
            if($token) {
                $state_data['token'] = $token;
                $state_data['hunter']['hunter_name'] = $hunter_name;
                $state_data['hunter']['hunter_id'] = $hunter_id;
                $state_data['hunter']['hunter_passwd'] = $password;
            }
        }
        return $state_data;
    }

    /**
     * 获取微信用户个人信息
     * @param string $code
     * @param string $api_type
     * @return array
     */
    public function getWxUserInfo($code, $api_type = ''){
        $weixin_appid = C('weixin_appid');
        $weixin_secret = C('weixin_secret');
        if($api_type == 'api'){
            $weixin_appid = C('app_weixin_appid');
            $weixin_secret = C('app_weixin_secret');
        }
        if($api_type == 'wap'){
            $weixin_appid = C('wap_weixin_appid');
            $weixin_secret = C('wap_weixin_secret');
        }
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$weixin_appid.'&secret='.$weixin_secret.
            '&code='.$code.'&grant_type=authorization_code';
        $access_token = $this->getUrlContents($url);//通过code获取access_token
        $code_info = json_decode($access_token, true);
        $user_info = array();
        if(!empty($code_info['access_token'])) {
            $token = $code_info['access_token'];
            $openid = $code_info['openid'];
            $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$token.'&openid='.$openid;
            $result = $this->getUrlContents($url);//获取用户个人信息
            $user_info = json_decode($result, true);
            if(empty($user_info['unionid'])) {
                $user_info['unionid'] = $user_info['openid'];
            }
            $weixin_info = array();
            $weixin_info['unionid'] = $user_info['unionid'];
            $weixin_info['nickname'] = $user_info['nickname'];
            $weixin_info['openid'] = $user_info['openid'];
            $user_info['weixin_info'] = serialize($weixin_info);
        }
        return $user_info;
    }

    /**
     * 获取微信用户个人信息
     * @param string $code
     * @param string $api_type
     * @return array
     */
    public function getWxUserInfoUmeng($access_token, $openid){
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid;
        $result = $this->getUrlContents($url);//获取用户个人信息
        $user_info = json_decode($result, true);
        if(empty($user_info['unionid'])) {
            $user_info['unionid'] = $user_info['openid'];
        }
        $weixin_info = array();
        $weixin_info['unionid'] = $user_info['unionid'];
        $weixin_info['nickname'] = $user_info['nickname'];
        $weixin_info['openid'] = $user_info['openid'];
        $user_info['weixin_info'] = serialize($weixin_info);
        return $user_info;
    }


    /**
     * 获取新浪OAuth2的authorize接口
     * @param string $sina_type
     * @return array
     */
    public function getSinaOAuth2Url($sina_type = ''){
        $client_id = C('sina_wb_akey');
        $client_secret = C('sina_wb_skey');

        require_once (BASE_RESOURCE_PATH.DS.'api'.DS.'sina'.DS.'saetv2.ex.class.php');
        $oauth2 = new SaeTOAuthV2($client_id, $client_secret);

        $api_url = RESOURCE_SITE_URL.'/api/sina/return_url.php';
        $sina_url = '';
        if($sina_type == 'api'){//WAP接口调用
            $sina_url = $oauth2->getAuthorizeURL($api_url, 'code', 'api'.base64_encode($_GET['ref_url']), 'mobile');
        } else {
            $sina_url = $oauth2->getAuthorizeURL($api_url, 'code', base64_encode($_GET['ref_url']));
        }
        return $sina_url;
    }

    /**
     * 获取新浪微博用户个人信息
     * @param string $code
     * @return array
     */
    public function getSinaUserInfo($code, $client = '', $token = array()){
        $client_id = C('sina_wb_akey');
        $client_secret = C('sina_wb_skey');
        if($client == 'ios' || $client == 'android'){
            $client_id = C('app_sina_akey');
            $client_secret = C('app_sina_skey');
        }

        require_once (BASE_RESOURCE_PATH.DS.'api'.DS.'sina'.DS.'saetv2.ex.class.php');
        $oauth2 = new SaeTOAuthV2($client_id, $client_secret);

        if(!empty($code)){
            $api_url = RESOURCE_SITE_URL.'/api/sina/return_url.php';
            $params = array();
            $params['code'] = $code;
            $params['redirect_uri'] = $api_url;
            $token = $oauth2->getAccessToken('code', $params);
        }

        $oauth2->setToken($token['access_token']);
        $info = $oauth2->getUserById($token['uid']);//根据ID获取用户等基本信息
        return $info;
    }

    /**
     * 新浪注册
     * @param string $user_info
     * @param string $client
     * @return array
     */
    public function sinaRegister($user_info, $client){
        $state_data = array();
        $state_data['token'] = 0;
        $openid = $user_info['id'];
        $nickname = $user_info['screen_name'];
        $sina_str = serialize($user_info);
        $rand = rand(100, 899);
        $hunter_name = $this->gethunterName($nickname, $rand);
        $password = rand(100000, 999999);
        $hunter = array();
        $hunter['hunter_name'] = $hunter_name;
        $hunter['hunter_passwd'] = $password;
        $hunter['hunter_email'] = '';
        $hunter['hunter_sinaopenid'] = $openid;
        $hunter['hunter_sinainfo'] = $sina_str;
        $model_hunter = Model('hunter');
        $result = $model_hunter->addhunter($hunter);
        if($result) {
            $avatar = @copy($user_info['avatar_large'],BASE_UPLOAD_PATH.'/'.ATTACH_AVATAR."/avatar_$result.jpg");
            if($avatar) {
                $model_hunter->edithunter(array('hunter_id'=> $result),array('hunter_avatar'=> "avatar_$result.jpg"));
            }
            $hunter = $model_hunter->gethunterInfo(array('hunter_name'=> $hunter_name));
            if($client == 'www'){//网站注册
                $hunter['password'] = $password;
                return $hunter;
            }
            $hunter_id = $hunter['hunter_id'];
            $token = $this->getUserToken($hunter, $client);//手机接口登录
            if($token) {
                $state_data['token'] = $token;
                $state_data['hunter']['hunter_name'] = $hunter_name;
                $state_data['hunter']['hunter_id'] = $hunter_id;
                $state_data['hunter']['hunter_passwd'] = $password;
            }
        }
        return $state_data;
    }

    /**
     * 获取qq接口
     * @param string $qq_type
     * @return array
     */
    public function getQqOAuth2Url($qq_type = ''){
        $client_id = C('qq_appid');
        $client_secret = C('qq_appkey');

        require_once (BASE_RESOURCE_PATH.DS.'api'.DS.'qq'.DS.'oauth.qq.class.php');
        $oauth2 = new OauthQq($client_id, $client_secret);

        $api_url = RESOURCE_SITE_URL.'/api/qq/return_url.php';
        $qq_url = '';
        if($qq_type == 'api'){//WAP接口调用
            $qq_url = $oauth2->qq_login($api_url, 'api'.base64_encode($_GET['ref_url']), 'mobile');
        } else {
            $qq_url = $oauth2->qq_login($api_url, base64_encode($_GET['ref_url']));
        }
        return $qq_url;
    }

    /**
     * 获取qq用户个人信息
     * @param string $code
     * @return array
     */
    public function getQqUserInfo($code, $client = '', $token = ''){
        $client_id = C('qq_appid');
        $client_secret = C('qq_appkey');
        if($client == 'ios' || $client == 'android'){
            $client_id = C('app_qq_akey');
            $client_secret = C('app_qq_skey');
        }

        require_once (BASE_RESOURCE_PATH.DS.'api'.DS.'qq'.DS.'oauth.qq.class.php');
        $oauth2 = new OauthQq($client_id, $client_secret);
        $token = '';
        if(!empty($code)){
            $api_url = RESOURCE_SITE_URL.'/api/qq/return_url.php';
            $token = $oauth2->qq_callback($api_url, $code);
        }
        $get_unionid = 0;
        $user = $oauth2->get_openid($token,$get_unionid);
        $openid = $user["openid"];
        $unionid = $user["unionid"];
        $info = array();
        if($client == 'ios' || $client == 'android'){$openid = $_GET['open_id'];$unionid = $_GET['union_id'];
            $info = $oauth2->get_user_info_simple($token, $openid);//根据ID获取用户等基本信息,此接口仅支持移动端应用调用
            if(empty($info['nickname'])){
                $openid = $_GET['open_id'];
                $unionid = $_GET['union_id'];
                $info['openid'] = $openid;
                $info['nickname'] = 'qq';
                if(!empty($_GET['nickname'])) $info['nickname'] = $_GET['nickname'];
                if(!empty($_GET['avatar'])) $info['figureurl_qq_2'] = $_GET['avatar'];
            }
        } else {
            $info = $oauth2->get_user_info($token, $openid);//根据ID获取用户等基本信息
        }

        if(!empty($info['nickname'])){
            if($unionid) $openid = $unionid;
            $info['openid'] = $openid;
        }
        return $info;
    }

    /**
     * qq注册
     * @param string $user_info
     * @param string $client
     * @return array
     */
    public function qqRegister($user_info, $client){
        $state_data = array();
        $state_data['token'] = 0;
        $openid = $user_info['openid'];
        $nickname = $user_info['nickname'];
        if (!preg_match('/^[A-Za-z0-9\x{4e00}-\x{9fa5}_]/u',$nickname)) $nickname='qq';
        $qq_str = serialize($user_info);
        $rand = rand(100, 899);
        $hunter_name = $this->gethunterName($nickname, $rand);
        $password = rand(100000, 999999);
        $hunter = array();
        $hunter['hunter_name'] = $hunter_name;
        $hunter['hunter_passwd'] = $password;
        $hunter['hunter_email'] = '';
        $hunter['hunter_qqopenid'] = $openid;
        $hunter['hunter_qqinfo'] = $qq_str;
        $model_hunter = Model('hunter');
        $result = $model_hunter->addhunter($hunter);
        if($result) {
            $avatar = @copy($user_info['figureurl_qq_2'],BASE_UPLOAD_PATH.'/'.ATTACH_AVATAR."/avatar_$result.jpg");
            if($avatar) {
                $model_hunter->edithunter(array('hunter_id'=> $result),array('hunter_avatar'=> "avatar_$result.jpg"));
            }
            $hunter = $model_hunter->gethunterInfo(array('hunter_name'=> $hunter_name));
            if($client == 'www'){//网站注册
                $hunter['password'] = $password;
                return $hunter;
            }
            $hunter_id = $hunter['hunter_id'];
            $token = $this->getUserToken($hunter, $client);//手机接口登录
            if($token) {
                $state_data['token'] = $token;
                $state_data['hunter']['hunter_name'] = $hunter_name;
                $state_data['hunter']['hunter_id'] = $hunter_id;
                $state_data['hunter']['hunter_passwd'] = $password;
            }
        }
        return $state_data;
    }

    /**
     * OAuth2.0授权认证
     * @param string $url
     * @return string
     */
    public function getUrlContents($url){
        if (ini_get("allow_url_fopen") == "1") {
            return file_get_contents($url);
        } else {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($ch, CURLOPT_URL, $url);
            $result = curl_exec($ch);
            curl_close($ch);
            return $result;
        }
    }
}
